package com.atguigu.daijia.customer.controller;

import com.atguigu.daijia.common.login.DaiJiaLogin;
import com.atguigu.daijia.common.result.Result;
import com.atguigu.daijia.common.util.AuthContextHolder;
import com.atguigu.daijia.customer.service.OrderService;
import com.atguigu.daijia.model.form.customer.ExpectOrderForm;
import com.atguigu.daijia.model.form.customer.SubmitOrderForm;
import com.atguigu.daijia.model.form.map.CalculateDrivingLineForm;
import com.atguigu.daijia.model.form.order.UpdateOrderCartForm;
import com.atguigu.daijia.model.form.payment.CreateWxPaymentForm;
import com.atguigu.daijia.model.form.payment.PaymentInfoForm;
import com.atguigu.daijia.model.vo.customer.ExpectOrderVo;
import com.atguigu.daijia.model.vo.driver.DriverInfoVo;
import com.atguigu.daijia.model.vo.map.DrivingLineVo;
import com.atguigu.daijia.model.vo.map.OrderLocationVo;
import com.atguigu.daijia.model.vo.map.OrderServiceLastLocationVo;
import com.atguigu.daijia.model.vo.order.CurrentOrderInfoVo;
import com.atguigu.daijia.model.vo.order.OrderInfoVo;
import com.atguigu.daijia.model.vo.payment.WxPrepayVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Slf4j
@Tag(name = "订单API接口管理")
@RestController
@RequestMapping("/order")
@SuppressWarnings({"unchecked", "rawtypes"})
public class OrderController {


    @Autowired
    private OrderService orderService;


    @Operation(summary = "乘客端查找当前订单")
    @DaiJiaLogin
    @GetMapping("/searchCustomerCurrentOrder")
    public Result<CurrentOrderInfoVo> searchCustomerCurrentOrder() {
        Long customerId = AuthContextHolder.getUserId();
        return Result.ok(orderService.searchCustomerCurrentOrder(customerId));
    }

    @Operation(summary = "获取订单信息")
    @DaiJiaLogin
    @GetMapping("/getOrderInfo/{orderId}")
    public Result<OrderInfoVo> getOrderInfo(@PathVariable Long orderId) {
        Long customerId = AuthContextHolder.getUserId();
        return Result.ok(orderService.getOrderInfo(orderId, customerId));
    }


    @Operation(summary = "预估订单数据")
    @DaiJiaLogin
    @PostMapping("/expectOrder")
    public Result<ExpectOrderVo> expectOrder(@RequestBody ExpectOrderForm expectOrderForm) {
        return Result.ok(orderService.expectOrder(expectOrderForm));
    }
    @Operation(summary = "乘客下单")
    @DaiJiaLogin
    @PostMapping("/submitOrder")
    public Result<Long> submitOrder(@RequestBody SubmitOrderForm submitOrderForm){
        submitOrderForm.setCustomerId(AuthContextHolder.getUserId());
        return Result.ok(orderService.submitOrder(submitOrderForm));
    }
    @Operation(summary = "查询订单状态")
    @DaiJiaLogin
    @GetMapping("/getOrderStatus/{orderId}")
    public Result<Integer> getOrderStatus(@PathVariable Long orderId) {
        return Result.ok(orderService.getOrderStatus(orderId));
    }
    @Operation(summary = "根据订单id获取司机基本信息")
    @DaiJiaLogin
    @GetMapping("/getDriverInfo/{orderId}")
    public Result<DriverInfoVo> getDriverInfo(@PathVariable Long orderId) {
        Long customerId = AuthContextHolder.getUserId();
        return Result.ok(orderService.getDriverInfo(orderId, customerId));
    }

    @Operation(summary = "司机赶往代驾起始点：获取订单经纬度位置")
    @DaiJiaLogin
    @GetMapping("/getCacheOrderLocation/{orderId}")
    public Result<OrderLocationVo> getOrderLocation(@PathVariable Long orderId) {
        return Result.ok(orderService.getCacheOrderLocation(orderId));
    }


    @Operation(summary = "计算最优路线")
    @DaiJiaLogin
    @PostMapping("/calculateDrivingLine")
    public  Result<DrivingLineVo> calculDrivingLine(@RequestBody CalculateDrivingLineForm calculateDrivingLineForm){
        return Result.ok(orderService.calculDrivingLine(calculateDrivingLineForm));
    }


    @Operation(summary = "创建微信支付")
    @GetMapping("/createWxPayment")
    public Result subWxOrder(@RequestBody PaymentInfoForm paymentInfoForm) throws Exception {
        //查询订单信息

        //1.从数据库查询(订单名称,订单编号,订单金额)
        String body = "帮帮代驾";    //订单名称(商品名称)
        String orderId = paymentInfoForm.getOrderNo();  //订单编号(这里的订单编号不可重复，建议使用UUID+时间戳的方式实现)
        String money = "1";         //订单金额(分)
        //3.调用微信工具类,把订单发给微信
        Map<String, String> payMap = orderService.createNative(body, orderId, money);
        if (payMap == null) {
            throw new RuntimeException("下单失败,请稍后重试!");
        }
        //4.判断下单是否正常
        String return_code = payMap.get("return_code");
        if (!return_code.equals("SUCCESS")) {
            //获取错误信息
            String return_msg = payMap.get("return_msg");
            throw new RuntimeException(return_msg);
        }
        //5.如果成功,则获取生成的支付Url
        String code_url = payMap.get("code_url");
        return Result.ok(code_url);
    }

    @Operation(summary = "支付状态查询")
    @GetMapping("/queryPayStatus/{orderNo}")
    public Result findPayStatus(@PathVariable String orderNo){
        //1.根据订单号,去微信中,查询订单状态
        Map<String, String> checkMap = orderService.queryNative(orderNo);
        //2.获取请求结果
        String return_code = checkMap.get("return_code");
        if (return_code.equals("SUCCESS")) {
            //3.获取订单状态
            String trade_state = checkMap.get("trade_state");
            if (trade_state.equals("SUCCESS")) {
                // 订单已经支付
                // 修改订单状态(修改数据库中的订单状态)
                // 响应前端支付成功的信息 前端做出相应的提示
            } else if (trade_state.equals("PAYERROR")) {
                // 支付失败!
                // 修改订单状态(修改数据库中的订单状态);
            } else if (trade_state.equals("CLOSED")) {
                // 订单超时,已关闭!
                // 修改订单状态(修改数据库中的订单状态);
            } else if (trade_state.equals("NOTPAY")) {
                // 未支付!
            } else if (trade_state.equals("USERPAYING")) {
                // 支付中!
            } else if (trade_state.equals("REFUND")) {
                // 已取消
            }
            return Result.ok(trade_state);
        } else {
            // 获取请求失败原因
            String return_msg = checkMap.get("return_msg");
            throw new RuntimeException(return_msg);
        }
    }

    @Operation(summary = "代驾服务：获取订单服务最后一个位置信息")
    @DaiJiaLogin
    @GetMapping("/getOrderServiceLastLocation/{orderId}")
    public Result<OrderServiceLastLocationVo> getOrderServiceLastLocation(@PathVariable Long orderId) {
        return Result.ok(orderService.getOrderServiceLastLocation(orderId));
    }

}

